package com.hhit.collaborative_learning.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import com.hhit.collaborative_learning.dao.TeamDao;
import com.mysql.jdbc.Statement;
import com.mysql.jdbc.StringUtils;

public class TeamDaoImpl implements TeamDao {

	@Override
	public ResultSet query(Connection con, int start, int end, String find,
			String order, String sort) {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM collaborative_learning.team ";
		if (!StringUtils.isNullOrEmpty(find)) {
			sql += " where " + find;
		}
		if (!StringUtils.isNullOrEmpty(sort)) {
			sql += " order by " + sort;
			if (!StringUtils.isNullOrEmpty(order)) {
				sql += " " + order;
			}
		}
		if (end != 0 && start < end) {
			sql += " limit " + start + "," + end;
		}
		PreparedStatement prs;
		try {
			prs = con.prepareStatement(sql);
			return prs.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("非法请求：" + sql);
			return null;
		}
	}

	@Override
	public int insert(Connection con, String name, String creator, String desc) {
		// TODO Auto-generated method stub
		int id = 0;
		String sql = "INSERT INTO `collaborative_learning`.`team`(`Name`,`Creator`,`CreatedOn`,`Desc`) VALUES(?,?,?,?)";
		try {
			PreparedStatement prs = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			prs.setString(1, name);
			prs.setInt(2, Integer.valueOf(creator));
			prs.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
			prs.setString(4, desc);
			prs.executeUpdate();
			ResultSet rs = prs.getGeneratedKeys();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			return id;
		} catch (SQLException ex) {
			ex.printStackTrace();
			return 0;
		}
	}

}
